import { defineStore } from "pinia";
import { ref } from "vue";
import { Auth, Menu } from "../apis/auth/type";
import { getMenus, getPublicKey, userLogin, wechatLogin } from "../apis/auth/auth";
import { sm2, sm3, sm4 } from 'sm-crypto'
import { TreeNode, flatToTree } from "../utils/treeUtil";

export const useAuthStore = defineStore("auth", () => {

   const token = ref<string|null>("");
   const permission = ref<TreeNode[]>([]);
   const menus = ref<TreeNode[]>([]);

   const permissionButtonId=ref<number[]>([]);


   const out=()=>{

      token.value=null;
      menus.value=[];
      permission.value=[];

      location.reload();//刷新刷新浏览器

   }

   const getMenu = async () => {

      if(permission.value.length ==0){
         const res = await getMenus();

         console.log("返回权限",res);

         permissionButtonId.value=res.data.list.map(item=>item.id);

         console.log(  permissionButtonId.value);
         
         
         //把扁平数据转成树状
         permission.value =  flatToTree(res.data.list);

         menus.value =  flatToTree(res.data.list.filter(item=>item.isButton===0));


      }
      return   permission.value;

   }

   const loginBycode = async (code: string) => {

      //请求返回公钥
      const res:any = await wechatLogin(code);

      console.log("扫码登录",res);
      if(res.data?.token){
         token.value=res.data?.token;
      }
      
      return res;
    
   }

   const login = async (data: Auth) => {

      //请求返回公钥
      const keyRes = await getPublicKey();
      let publicKey = keyRes.data;
      //加密
      let newPassword = sm2.doEncrypt(data.pwd, publicKey, 1);
      data.pwd = newPassword;
 
      const res = await userLogin(data).catch(() => undefined);
      if (res) {
         token.value = res.data.token;
         return true;
      }
   }
   return {
      token, login, getMenu,menus,out,loginBycode,permissionButtonId
   }


}, {
   persist: true
}

)